package com.yuncheng.spcyApi.flowService;

import com.yuncheng.entity.YcSysOrg;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.vo.GetKsKz;
import com.yuncheng.vo.CurrentUserVo;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.bo.UserPxjlBo;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.flow.NdkpConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.mapper.SpcySqsxXpjlMapper;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.service.impl.YcSysUserServiceImpl;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;

import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.flow.AgentVo;
import com.yuncheng.spcyApi.vo.ndkp.NdkpFlowMapVo;
import com.yuncheng.spcyApi.vo.ndkp.NdkpXpjlVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@Component(value = "ndkpFlowService")
public class NdkpFlowService extends FlowService  {
    private static final Logger log = LoggerFactory.getLogger(NdkpFlowService.class);

    @Resource
    @Lazy
    private NdkpConstant flowConstant;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private ISysUserFgldService sysUserFgldService;

    @Resource
    @Lazy
    private YcSysUserServiceImpl ycSysUserService;

    @Resource
    @Lazy
    private IYcSysOrgService ycSysOrgService;

    @Resource
    @Lazy
    private SpcySqsxXpjlMapper spcySqsxXpjlMapper;

    @Resource
    @Lazy
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    @Lazy
    private ISpcyKpNdkpBasicService spcyKpNdkpBasicService;

    @Resource
    @Lazy
    private ISysUserPxjlService sysUserPxjlService;

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    public Result handleFlow(NdkpFlowMapVo ypscFlowVo, SpcySqsxJob nowJob, String jobId, String ndkpid, String submitType, String opinion){
        // 当前流程任务
        if (StringUtils.isNotBlank(jobId)) {
            nowJob = spcySqsxJobService.getById(jobId);
        }

        if (nowJob == null){
            return Result.error("当前流程任务不存在，请重试");
        }

        // 提交按钮
        if (submitType.equals(NdkpConstant.SUBMIT_TYPE_SUBMIT)) {
            if (nowJob == null) {
                return Result.error("当前流程任务不存在");
            }
        }

        // 流程环节处理
        Result httpResult = handleNodeName(ypscFlowVo, submitType, nowJob, ndkpid, opinion);
        if (!httpResult.isSuccess()){
            return httpResult;
        }else {
            // 最后一个环节提交
            if(submitType.equals(NdkpConstant.SUBMIT_TYPE_SUBMIT) && nowJob.equals(NdkpConstant.HJMC_DSPRW)){
                SpcyKpNdkpBasic ndkp = spcyKpNdkpBasicService.getById(ndkpid);
                if (ndkp != null) {
                    ndkp.setFlczt(NdkpConstant.HJMC_LCJS);
                    ndkp.setFwcsj(new Date());
                    spcyKpNdkpBasicService.updateById(ndkp);
                }
            }
        }
        return httpResult;

    }

    public Result handleNodeName(NdkpFlowMapVo ypscFlowVo,String submitType, SpcySqsxJob job, String ndkpid, String opinion){
        HashMap<String, Object> map = ypscFlowVo.getMap();
        String dbrid = ypscFlowVo.getDbrid();// 下环节待办人
        String smgflag = ypscFlowVo.getSmgflag(); // 短信发送标志

        Result res = null;

        // 保存按钮
        if (submitType.equals(NdkpConstant.SUBMIT_TYPE_SAVE)){
            Result result = this.updateKpxx(ndkpid, map);
            if (!result.isSuccess()){
                return result;
            }
        }

        // 提交按钮
        if (submitType.equals(NdkpConstant.SUBMIT_TYPE_SUBMIT)){
            Result result = this.updateKpxx(ndkpid, map);
            if (!result.isSuccess()){
                return result;
            }

            // 流程任务id
            String jobId = "";
            if (job != null){
                jobId = job.getId();
            }

            // 个人总结
            if (job.getFhjmc().equals(NdkpConstant.HJMC_GRZJ)){
                dbrid = "";
                Map nodeDbr = this.getNodeDbr(ndkpid, flowConstant.getNextNodeName(NdkpConstant.HJMC_GRZJ), "");
                dbrid = nodeDbr.get("dbrId").toString();
            }

            // 提交流程任务,待办人是否为空，指定待办人
            if (StringUtils.isBlank(dbrid)) {
                // 提交-流程任务
                res = this.passJob(ndkpid, jobId, opinion, "", "");
            }else {
                // 提交-流程任务
                res = this.passJob(ndkpid, jobId, opinion, "", dbrid);
            }
            if (!res.isSuccess()){
                return res;
            }else {
                SpcySqsxJob nowJob = (SpcySqsxJob)res.getResult();
                // 接收返回的流程任务，如果返回的流程任务id不相等，发送短信
                if (nowJob != null && !jobId.equals(nowJob.getId()) && StringUtils.isNotBlank(smgflag) && smgflag.equals("是")){
                    busService.sendSmsToPassJob(nowJob);
                }
            }
        }

        return Result.ok("提交成功");
    }

    /**
     * 计算参与考评人员的记录
     */
    public void jsJoinKpxx(String ndkpid){
        SpcyKpNdkpBasic ndkp = spcyKpNdkpBasicService.getById(ndkpid);
        String fywflcode = "";
        String fuserid = "";
        String year = "";
        if (ndkp == null){
            return;
        }
        if (StringUtils.isNotBlank(ndkp.getFywflcode())){
            fywflcode = ndkp.getFywflcode();
        }
        if (StringUtils.isNotBlank(ndkp.getFuserid())){
            fuserid = ndkp.getFuserid();
        }
        if (StringUtils.isNotBlank(ndkp.getFyear())){
            year = ndkp.getFyear();
        }

        Map hcyYearTj = this.getHcyYearTj(fuserid, fywflcode, year);
        ndkp.setFzxxpcs((Integer) hcyYearTj.get("zxxpcs"));
        ndkp.setFsjjccs((Integer) hcyYearTj.get("sjjccs"));
        ndkp.setFjcqyzs((Integer) hcyYearTj.get("jcqxzs"));
        ndkp.setFdrzzcs((Integer) hcyYearTj.get("drzzcs"));
        ndkp.setFdrzycs((Integer) hcyYearTj.get("drzycs"));
        ndkp.setFcjjccs((Integer) hcyYearTj.get("cjjccs"));
        ndkp.setFcjpscs((Integer) hcyYearTj.get("cjspcs"));
        ndkp.setFcql(hcyYearTj.get("attendance").toString());

        spcyKpNdkpBasicService.updateById(ndkp);
    }

    /**
     * 获取 核查员年度的统计
     */
    public Map getHcyYearTj(String fuserid,String fywflcode,String year){
        Map map = new HashMap();

        int xpcs = 0; // 选派次数

        int btyxpcs = 0; // 不同意选派次数

        int tyxpcs = 0; // 同意选派次数

        int zxxpcs = 0; // 中心选派次数

        int sjjccs = 0; // 实际检查次数

        int jcqxzs = 0; // 检查企业总数

        int drzzcs = 0;  // 担任组长次数

        int drzycs = 0; // 担任组员次数

        int cjjccs = 0; // 参加检查次数

        int cjspcs = 0; // 参加评审次数

        String attendance = "0"; // 出勤率

        NdkpXpjlVo ndkpXpjlVo = new NdkpXpjlVo();
        ndkpXpjlVo.setFuserid(fuserid);
        ndkpXpjlVo.setFywflcode(fywflcode);
        ndkpXpjlVo.setYear(year);
        List<NdkpXpjlVo> xpjlVoList = spcySqsxXpjlMapper.getNdkpXpjl(ndkpXpjlVo);
        if (CollectionUtils.isEmpty(xpjlVoList)){

        }else {
            // 中心选派次数
            zxxpcs = xpjlVoList.size();

            // 实际检查次数
            List<NdkpXpjlVo> sjjccsList = xpjlVoList.stream().filter(c -> StringUtils.isNotBlank(c.getFsftyxp()) &&
                    c.getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_YES)).collect(Collectors.toList());
            sjjccs = sjjccsList.size();

            if (CollectionUtils.isNotEmpty(sjjccsList)){
                // 检查企业总数
                List<String> sqsxIdList = new ArrayList<>();
                List<SpcySqsxBasic> sqsxList = new ArrayList<>();
                List<SpcySqsxBasic> distSqsxList = new ArrayList<>();
                sqsxIdList = sjjccsList.stream().map(NdkpXpjlVo::getFsqsxid).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(sqsxIdList)) {
                    sqsxList = spcySqsxBaiscService.listByIds(sqsxIdList);
                }
                if (CollectionUtils.isNotEmpty(sqsxList)) {
                    distSqsxList = sqsxList.stream().distinct().collect(Collectors.toList());
                }
                jcqxzs = distSqsxList.size();

                // 担任组长次数
                List<NdkpXpjlVo> zzList = sjjccsList.stream().filter(c -> StringUtils.isNotBlank(c.getFssk()) &&
                        c.getFssk().contains(SpcyConstant.HCY_SSK_ZZ)).collect(Collectors.toList());
                drzzcs = zzList.size();

                // 担任组员次数
                List<NdkpXpjlVo> zyList = sjjccsList.stream().filter(c -> StringUtils.isNotBlank(c.getFssk()) &&
                        c.getFssk().contains(SpcyConstant.HCY_SSK_ZY)).collect(Collectors.toList());
                drzycs = zyList.size();

            }

            // 查验
            List<NdkpXpjlVo> cyXpList = xpjlVoList.stream().filter(c -> StringUtils.isNotBlank(c.getFspcylx()) &&
                    c.getFspcylx().equals(SpcyConstant.FLOW_TYPE_CY)).collect(Collectors.toList());

            // 审评
            List<NdkpXpjlVo> spXpList = xpjlVoList.stream().filter(c -> StringUtils.isNotBlank(c.getFspcylx()) &&
                    c.getFspcylx().equals(SpcyConstant.FLOW_TYPE_SP)).collect(Collectors.toList());

            // 参加检查次数
            List<NdkpXpjlVo> cjjcList = cyXpList.stream().filter(c -> StringUtils.isNotBlank(c.getFsftyxp()) &&
                    c.getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_YES)).collect(Collectors.toList());
            cjjccs = cjjcList.size();
            tyxpcs = cjjcList.size(); // 查验-同意选派次数

            // 不同意选派次数
            List<NdkpXpjlVo> btyxpcsList = cyXpList.stream().filter(c -> StringUtils.isNotBlank(c.getFsftyxp()) &&
                    c.getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_NO)).collect(Collectors.toList());
            btyxpcs = btyxpcsList.size(); // 查验-不同意选派次数

            // 参加评审次数
            List<NdkpXpjlVo> cjspcsList = spXpList.stream().filter(c -> StringUtils.isNotBlank(c.getFsftyxp()) &&
                    c.getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_YES)).collect(Collectors.toList());
            cjspcs = cjspcsList.size();

            attendance = spcySqsxXpjlService.jsNdkpCql(zxxpcs, sjjccs); // 出勤率
        }

        xpcs = tyxpcs + btyxpcs; // 查验-总选派次数
        map.put("xpcs",xpcs);
        map.put("btyxpcs",btyxpcs);
        map.put("tyxpcs",tyxpcs);
        map.put("zxxpcs",zxxpcs);
        map.put("sjjccs",sjjccs);
        map.put("jcqxzs",jcqxzs);
        map.put("drzzcs",drzzcs);
        map.put("drzycs",drzycs);
        map.put("cjjccs",cjjccs);
        map.put("cjspcs",cjspcs);
        map.put("attendance",attendance);

        return map;
    }


    /**
     * 获取年度选派统计
     */
    public SpcyKpNdkpBasic getNdXpTj(String fywflcode,String year){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        String fuserid = currentUser.getId();

        SpcyKpNdkpBasic ndkp = new SpcyKpNdkpBasic();

        NdkpXpjlVo ndkpXpjlVo = new NdkpXpjlVo();
        ndkpXpjlVo.setFuserid(fuserid);
        ndkpXpjlVo.setFywflcode(fywflcode);
        ndkpXpjlVo.setYear(year);
        List<NdkpXpjlVo> xpjlVoList = spcySqsxXpjlMapper.getNdkpXpjl(ndkpXpjlVo);
        if (CollectionUtils.isEmpty(xpjlVoList)){
            ndkp.setFzxxpcs(0);
            ndkp.setFsjjccs(0);
            ndkp.setFjcqyzs(0);
            ndkp.setFdrzzcs(0);
            ndkp.setFdrzycs(0);
            ndkp.setFcjjccs(0);
            ndkp.setFcjpscs(0);
            ndkp.setFcql("0");
            return ndkp;
        }

        // 中心选派次数
        int zxxpcs = 0;
        zxxpcs = xpjlVoList.size();

        // 实际检查次数
        int sjjccs = 0;
        List<NdkpXpjlVo> sjjccsList = xpjlVoList.stream().filter(c -> StringUtils.isNotBlank(c.getFsftyxp()) &&
                c.getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_YES)).collect(Collectors.toList());
        sjjccs = sjjccsList.size();

        // 检查企业总数
        int jcqxzs = 0;
        List<String> sqsxIdList = new ArrayList<>();
        List<SpcySqsxBasic> sqsxList = new ArrayList<>();
        List<SpcySqsxBasic> distSqsxList = new ArrayList<>();
        sqsxIdList = xpjlVoList.stream().map(NdkpXpjlVo::getFsqsxid).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(sqsxIdList)){
            sqsxList = spcySqsxBaiscService.listByIds(sqsxIdList);
        }
        if (CollectionUtils.isNotEmpty(sqsxList)){
            distSqsxList = sqsxList.stream().distinct().sorted().collect(Collectors.toList());
        }
        jcqxzs = distSqsxList.size();

        // 担任组长次数
        int drzzcs = 0;
        List<NdkpXpjlVo> zzList = xpjlVoList.stream().filter(c -> StringUtils.isNotBlank(c.getFssk()) &&
                c.getFssk().contains(SpcyConstant.HCY_SSK_ZZ)).collect(Collectors.toList());
        drzzcs = zzList.size();

        // 担任组员次数
        int drzycs = 0;
        List<NdkpXpjlVo> zyList = xpjlVoList.stream().filter(c -> StringUtils.isNotBlank(c.getFssk()) &&
                c.getFssk().contains(SpcyConstant.HCY_SSK_ZY)).collect(Collectors.toList());
        drzycs = zyList.size();

        // 查验
        List<NdkpXpjlVo> cyXpList = xpjlVoList.stream().filter(c -> StringUtils.isNotBlank(c.getFspcylx()) &&
                c.getFspcylx().equals(SpcyConstant.FLOW_TYPE_CY)).collect(Collectors.toList());

        // 审评
        List<NdkpXpjlVo> spXpList = xpjlVoList.stream().filter(c -> StringUtils.isNotBlank(c.getFspcylx()) &&
                c.getFspcylx().equals(SpcyConstant.FLOW_TYPE_SP)).collect(Collectors.toList());

        // 参加检查次数
        int cjjccs = 0;
        List<NdkpXpjlVo> cjjcList = cyXpList.stream().filter(c -> StringUtils.isNotBlank(c.getFsftyxp()) &&
                c.getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_YES)).collect(Collectors.toList());
        cjjccs = cjjcList.size();

        // 参加评审次数
        int cjspcs = 0;
        List<NdkpXpjlVo> cjspcsList = spXpList.stream().filter(c -> StringUtils.isNotBlank(c.getFsftyxp()) &&
                c.getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_YES)).collect(Collectors.toList());
        cjspcs = cjspcsList.size();

        String attendance = spcySqsxXpjlService.jsNdkpCql(zxxpcs, sjjccs); // 出勤率

        ndkp.setFzxxpcs(zxxpcs);
        ndkp.setFsjjccs(sjjccs);
        ndkp.setFjcqyzs(jcqxzs);
        ndkp.setFdrzzcs(drzzcs);
        ndkp.setFdrzycs(drzycs);
        ndkp.setFcjjccs(cjjccs);
        ndkp.setFcjpscs(cjspcs);
        ndkp.setFcql(attendance);

        return ndkp;
    }



    public Result updateKpxx(String ndkpid,HashMap<String,Object> buffer){
        if (StringUtils.isBlank(ndkpid)){
            return Result.error("年度考评id不能存在");
        }
        SpcyKpNdkpBasic updateNdkp = spcyKpNdkpBasicService.getById(ndkpid);
        if (updateNdkp == null){
            return Result.error("当前年度考评信息不存在，请重试");
        }
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(updateNdkp);

        // 修改
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        try {
            BeanUtils.populate(updateNdkp, buffer);
        }catch (IllegalAccessException e) {
            log.error("出错-保存年度考评【非法访问异常 ，llegalAccessException】,{}",e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("出错-保存年度考评【调用TargetException，InvocationTargetException】,{}",e.getMessage());
        }
        spcyKpNdkpBasicService.updateById(updateNdkp);

        String logContent = "基本信息修改: ";
        logContent += LogUtils.BeanModifyMsg(updateNdkp,oldMap);
        spcyLogService.addLogs(LogConstant.LOGS_SQSX_BASIC, logContent, ndkpid, LogConstant.LOGS_RS_YWZDXX, SpcyConstant.LOGS_SYS_TYPE_XG);

        return Result.ok();
    }

    /**
     * 获取当前流程任务相关信息
     * @param jobid 流程任务id
     */
    public Map getJobConcernByJobId(String jobid){
        Map map = new HashMap();

        // 当前流转记录
        SpcySqsxJob job = spcySqsxJobService.getById(jobid);
        if (job == null){
            log.error("当前流程任务id为【{}】的流转记录不存在",jobid);
            return map;
        }
        String ndkpid = job.getFpid();
        if (org.apache.commons.lang3.StringUtils.isBlank(ndkpid)){
            log.error("当前流程任务id为【{}】的流转记录中的年度考评id为空",jobid);
            return map;
        }

        // 申请事项基本信息
        SpcyKpNdkpBasic ndkpBasic = spcyKpNdkpBasicService.getById(ndkpid);

        // 流程任务流传记录
        List<String> nodeList = Arrays.asList(NdkpConstant.NODENAME.split(",")); // 所有环节名称
        LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxJob::getFpid, ndkpid);
        queryWrapper.in(SpcySqsxJob::getFhjmc,nodeList);
        queryWrapper.orderByAsc(SpcySqsxJob::getFfssj);
        queryWrapper.orderByAsc(SpcySqsxJob::getCreateTime);
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(queryWrapper);

        // 获取下环节待办人
        Map nextDbr = getNextDbr(ndkpid, jobid);
        String nextNode = nextDbr.get("nextNode").toString();
        List<AgentVo> dbrListByMap = busService.getDbrListByMap(nextDbr);

        // 培训情况
        List<SysUserPxjl> pxjlList = new ArrayList<>();
        if (ndkpBasic != null) {
            UserPxjlBo pxjl = new UserPxjlBo();
            pxjl.setFuserid(ndkpBasic.getFuserid());
            pxjlList = sysUserPxjlService.getList(pxjl, ndkpBasic.getFyear(), false);
        }

        map.put("ndkp",ndkpBasic); // 年度考评基本信息
        map.put("job",job); // 当前流转记录
        map.put("jobHistoryList",jobList); // 流程任务流传记录
        map.put("nextNodeDbrList",dbrListByMap); // 下环节待办人list
        map.put("nextNode",nextNode);
        map.put("pxjlList",pxjlList); // 培训情况

        return map;
    }

    /**
     * 获取当前流程环节名称
     * @param ndkpid 年度考评id
     * @return
     */
    public String getNowNodeName(String ndkpid){
        if (org.apache.commons.lang3.StringUtils.isBlank(ndkpid)){
            return "";
        }
        // 当前流转待办
        List<String> nodeList = Arrays.asList(NdkpConstant.NODENAME.split(","));
        // 查询属于这个流程的
        List<SpcySqsxJob> sqsxJob = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, ndkpid)
                .in(SpcySqsxJob::getFhjmc,nodeList)
                .eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_DB));
        if (CollectionUtils.isNotEmpty(sqsxJob)){
            return sqsxJob.get(0).getFhjmc();
        }

        return "";
    }

    /**
     * 获取下环节待办人
     * @param ndkpid 年度考评id
     */
    public Map getNextDbr(String ndkpid,String jobid){
        String jobNodeName = busService.getJobNodeName(jobid); // 获取当前流程任务job环节

        // 下一个环节名称
        String nextNodeName = flowConstant.getNextNodeName(jobNodeName);
        Map nodeDbr = new HashMap();
        nodeDbr = getNodeDbr(ndkpid, nextNodeName, "");

        nodeDbr.put("nextNode",nextNodeName);

        return nodeDbr;
    }

    // 验证是否存在进行任务
    public Result isInitNdkpJob(String ndkpid){
        String nodeName = flowConstant.getFirstNode();
        List<SpcySqsxJob> list = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, ndkpid)
                .eq(SpcySqsxJob::getFhjmc, nodeName)
        );
        if (CollectionUtils.isNotEmpty(list)){
            return Result.error("该年度考评信息已经初始化流程，权限不足，无法删除。");
        }
        return Result.ok("success");
    }

    //初始化任务
    public Result initJob(String pid, CurrentUserVo currentUser){
        String nodeName = flowConstant.getFirstNode();
        //需要校验是否已经初始化过
        List<SpcySqsxJob> list = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, pid)
                .eq(SpcySqsxJob::getFhjmc, nodeName)
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
        );
        if(list.size()>0){
            List<String> ids = list.stream().map(SpcySqsxJob::getId).collect(Collectors.toList());
            spcySqsxJobService.removeBatchByIds(ids);
        }
        return this.createNextJob(flowConstant,pid,null,currentUser,nodeName,"");
    }

    /**
     * 提交当前环节的待办记录
     *  @param sqsxId 申请事项id
     *  @param jobId 当前环节id
     *  @param opinion 办理意见
     */
    public Result passJob(String sqsxId, String jobId, String opinion,String nextNodeName,String nextNodeDbrIds){
        //处理业务表的逻辑
        Result httpResult = this.passJob(flowConstant, sqsxId, jobId, opinion, nextNodeName, nextNodeDbrIds);
        return httpResult;
    }

    // 获取当前环节待办人
    public Map getNodeDbr(String pid, String nodeName, String dbrIds){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        if(StringUtils.isNotBlank(dbrIds)){
            dbr = getDbrsByIds(dbrIds);
            dbrId = dbrIds;
        }else{
            String dept = "";
            String fywflcode = "";
            SpcyKpNdkpBasic ndkp = spcyKpNdkpBasicService.getById(pid);
            if (ndkp != null && StringUtils.isNotBlank(ndkp.getFywflcode())){
                fywflcode = ndkp.getFywflcode();
            }

            if (StringUtils.isNotBlank(fywflcode)){
                dept = SpcyConstant.getYwclNameByCode(fywflcode);
            }
            // 登记环节
            if (nodeName.equals(NdkpConstant.HJMC_KPDJ)){
                // 经办人
                Map kzMap = getKsjbrByDeptName(dept);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 个人总结
            if (nodeName.equals(NdkpConstant.HJMC_GRZJ)){
                dbrId = ndkp.getFuserid();
                dbr = ndkp.getFusermc();
            }

            // 待审核任务
            if (nodeName.equals(NdkpConstant.HJMC_DSHRW)){
                // 经办人
                Map kzMap = getKsjbrByDeptName(dept);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 待复核任务
            if (nodeName.equals(NdkpConstant.HJMC_DFHRW)){
                // 科室负责人
                Map kzMap = getKsfzrByDeptName(dept);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 待审批任务
            if (nodeName.equals(NdkpConstant.HJMC_DSPRW)){
                // 分管领导
                Map kzMap = getKsFgldByDeptName(dept);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取当前环节待办人
    public Map getNodeDbr(String nodeName, String dbrIds){
        return this.getNodeDbr(null,nodeName,dbrIds);
    }

    // 根据待办人id，获取名称拼接起来
    private String getDbrsByIds(String dbrIds){
        //把待办人按id查出来  把名字拼起来
        String dbr = "";
        List<String> dbrIdsList = Arrays.asList(dbrIds.split(","));
        List<YcSysUser> sysUserList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dbrIdsList)){
            sysUserList = ycSysUserService.listByIds(dbrIdsList);
        }

        if (CollectionUtils.isNotEmpty(sysUserList)){
            for (YcSysUser user : sysUserList){
                dbr += user.getRealname() + ",";
            }
        }

        return dbr;
    }

    // 对应科室的 经办人
    public Map getKsjbrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_JBR);

        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 对应科室的 科室负责人
    public Map getKsfzrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_KZ);
        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取对应科室的 分管领导
    public Map getKsFgldByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        YcSysUser fgldUserBydept = sysUserFgldService.getFgldUserBydept(deptName);
        if (fgldUserBydept != null) {
            dbrId = fgldUserBydept.getId();
            dbr = fgldUserBydept.getRealname();
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取中心主任
    public Map getZxzr(){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        List<YcSysOrg> org = ycSysOrgService.list(new LambdaQueryWrapper<YcSysOrg>()
                .like(YcSysOrg::getOrgName, SpcyConstant.ORG_NAME_ZXZR));

        if (CollectionUtils.isNotEmpty(org)){
            List<YcSysUser> user = ycSysUserService.list(new LambdaQueryWrapper<YcSysUser>()
                    .eq(YcSysUser::getOrgId, org.get(0).getId()));
            if (CollectionUtils.isNotEmpty(user)){
                dbrId = user.get(0).getId();
                dbr = user.get(0).getRealname();
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 退回流程
    public Result getReturnUpperFlowJob(String jobid,String opinion){
        if (StringUtils.isBlank(jobid)){
            return Result.error("当前流程任务id不能为空");
        }
        SpcySqsxJob job = spcySqsxJobService.getById(jobid);
        if (job == null){
            return Result.error("当前流程任务不存在");
        }
        // 办理状态 - 待办
        if (StringUtils.isNotBlank(job.getFblzt()) && (job.getFblzt().equals(SpcyConstant.BLZT_DB)
                || job.getFblzt().equals(SpcyConstant.BLZT_TH))){
            // 待办-获取上一个环节id
            String fsyhjid = job.getFsyhjid();
            SpcySqsxJob syhjJob = spcySqsxJobService.getById(fsyhjid);
            if (syhjJob != null){
                syhjJob.setFthyj(opinion);
                syhjJob.setFfssj(new Date());
                syhjJob.setFblzt(SpcyConstant.BLZT_TH);
                spcySqsxJobService.updateById(syhjJob);

                spcySqsxJobService.removeById(jobid); // 删除当前流程任务待办
            }
        }

        String logNr = "退回上一环节: ";
        Map<String, Object> map = ObjectToMapUtils.objectToMap(job);
        logNr += LogUtils.MapToStringMethod(map);
        spcyLogService.addLogs(job.getFhjmc(),logNr,job.getFpid(), LogConstant.LOGS_SQSX_JOB,SpcyConstant.LOGS_SYS_TYPE_TH);
        return Result.ok("success");
    }
}
